package com.edgclub.edg.fragment;

import android.app.Activity;
import android.content.Intent;
import android.graphics.drawable.AnimationDrawable;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.VolleyError;
import com.edgclub.edg.Constant;
import com.edgclub.edg.R;
import com.edgclub.edg.activity.FansMembersActivity;
import com.edgclub.edg.activity.FollowMembersActivity;
import com.edgclub.edg.activity.GzBindPhomeActivity;
import com.edgclub.edg.activity.GzMyGroupListActivity;
import com.edgclub.edg.activity.GzPayPassForgetActivity;
import com.edgclub.edg.activity.GzWebViewActivity;
import com.edgclub.edg.activity.GzWebViewActivityNoTitle;
import com.edgclub.edg.activity.MyInforMationActivity;
import com.edgclub.edg.activity.SettingActivity;
import com.edgclub.edg.activity.UserInfoActionActivity;
import com.edgclub.edg.api.ApiConfig;
import com.edgclub.edg.api.RechargeApi;
import com.edgclub.edg.api.ResultCode;
import com.edgclub.edg.api.UserApi;
import com.edgclub.edg.api.param.RechargeParam;
import com.edgclub.edg.api.param.UserParam;
import com.edgclub.edg.event.BroadCastEvent;
import com.edgclub.edg.event.EventBus;
import com.edgclub.edg.http.VolleyListener;
import com.edgclub.edg.model.User;
import com.edgclub.edg.model.result.UserHomeData;
import com.edgclub.edg.uc.DeleteDialog;
import com.edgclub.edg.utils.GlideUtil.GlideUtils;
import com.edgclub.edg.utils.GlideUtil.ImageLoaderClient;
import com.edgclub.edg.utils.util.AnimationUtil;
import com.edgclub.edg.utils.util.CryptUtil;
import com.edgclub.edg.utils.util.JSONHelper;
import com.edgclub.edg.utils.util.JsonUtil;
import com.edgclub.edg.utils.util.StringUtils;
import com.edgclub.edg.utils.util.UserPrefUtils;
import com.rockerhieu.emojicon.emoji.SerializeManager;
import com.squareup.otto.ThreadEnforcer;
import com.umeng.analytics.MobclickAgent;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;

/**
 * 频道切换
 */
public class MeFragment extends GzBaseFragment implements View.OnClickListener,VolleyListener {

	private RelativeLayout mBg_user;
	private RelativeLayout mSex_layout;
	private ImageView mIcon_user;
	private ImageView mVip;
	private TextView mUser_name,gold_num;
	private TextView mSign;
	private TextView mQiandao;
	private TextView mLv;
	private TextView mNum_time;
	private LinearLayout mPost;
	private TextView mPost_num;
	private LinearLayout mFollow;
	private TextView mFollow_num;
	private LinearLayout mFans;
	private TextView mFans_num , eid;
	private RelativeLayout mGold ;
	private ImageView mMy_gold_icon;
	private RelativeLayout mAward;
	private ImageView mMy_award_icon;
	private RelativeLayout mHonour;
	private ImageView mMy_honour_icon;
	private RelativeLayout mMoney;
	private ImageView mMy_bag_icon;
	private RelativeLayout mCollect;
	private ImageView mMy_collect_icon;
	private RelativeLayout mSetting;
	private ImageView mMy_setting_icon;
	private ArrayList<Fragment> fragmentList=new ArrayList<>();
	private UserPrefUtils userPrefUtils;
	private User user;
	private boolean isLoading;
	private  boolean isFirst=true;
	private GlideUtils glideUtils = new GlideUtils();
	private ImageLoaderClient imageLoaderClient;

	private LinearLayout group;
	private TextView group_num;
	private RelativeLayout auth_layout;
	private ImageView arrow_left , arrow_right;
	private RelativeLayout arrow_left_layout , arrow_right_layout;
	private TextView auth_text;
	private RelativeLayout auth_bg;

	public static MeFragment newInstance(String text) {
		MeFragment f = new MeFragment();
		return f;
	}
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
							 Bundle savedInstanceState) {
		View view = inflater.inflate(R.layout.fragment_me, container, false);
		initView(view);
		return view;
	}

	@Override
	public void onViewCreated(View view, Bundle savedInstanceState) {
		super.onViewCreated(view, savedInstanceState);
		initData();
	}


	@Override
	public void onCreate(@Nullable Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		EventBus.getEventBus(BroadCastEvent.EVENTBUS_COMMON,
				ThreadEnforcer.MAIN).register(this);
	}
	@Override
	public void onResume() {
		// TODO Auto-generated method stub
		super.onResume();

	}
	@Override
	public void onDestroy() {
		super.onDestroy();
		EventBus.getEventBus(BroadCastEvent.EVENTBUS_COMMON,
				ThreadEnforcer.MAIN).unregister(this);
	}

	private void initView(View view){
		auth_bg = (RelativeLayout) view.findViewById(R.id.auth_bg);
		auth_text = (TextView) view.findViewById(R.id.auth_text);
		arrow_left_layout  = (RelativeLayout) view.findViewById(R.id.arrow_left_layout);
		arrow_left = (ImageView) view.findViewById(R.id.arrow_left);
		arrow_left.setImageResource(R.drawable.loading_arrow_left);
		AnimationDrawable animationDrawable = (AnimationDrawable) arrow_left.getDrawable();
		animationDrawable.start();
		arrow_left_layout.setOnClickListener(this);

		arrow_right_layout  = (RelativeLayout) view.findViewById(R.id.arrow_right_layout);
		arrow_right = (ImageView) view.findViewById(R.id.arrow_right);
		arrow_right.setImageResource(R.drawable.loading_arrow_right);
		AnimationDrawable animationDrawable2 = (AnimationDrawable) arrow_right.getDrawable();
		animationDrawable2.start();
		arrow_right_layout.setOnClickListener(this);
		auth_layout = (RelativeLayout) view.findViewById(R.id.auth_layout);

		mBg_user = (RelativeLayout) view.findViewById(R.id.bg_user);
		mSex_layout = (RelativeLayout) view.findViewById(R.id.sex_layout);
		mIcon_user = (ImageView) view.findViewById(R.id.icon_user);
		mVip = (ImageView) view.findViewById(R.id.vip);
		mUser_name = (TextView) view.findViewById(R.id.user_name);
		mSign = (TextView) view.findViewById(R.id.sign);
		mQiandao = (TextView) view.findViewById(R.id.qiandao);
		mLv = (TextView) view.findViewById(R.id.lv);
		mNum_time = (TextView) view.findViewById(R.id.num_time);
		mPost = (LinearLayout) view.findViewById(R.id.post);
		mPost_num = (TextView) view.findViewById(R.id.post_num);
		mFollow = (LinearLayout) view.findViewById(R.id.follow);
		mFollow_num = (TextView) view.findViewById(R.id.follow_num);
		mFans = (LinearLayout) view.findViewById(R.id.fans);
		mFans_num = (TextView) view.findViewById(R.id.fans_num);
		gold_num = (TextView) view.findViewById(R.id.gold_num);
		mGold = (RelativeLayout) view.findViewById(R.id.gold);
		mMy_gold_icon = (ImageView) view.findViewById(R.id.my_gold_icon);
		mAward = (RelativeLayout) view.findViewById(R.id.award);
		mMy_award_icon = (ImageView) view.findViewById(R.id.my_award_icon);
		mHonour = (RelativeLayout) view.findViewById(R.id.honour);
		mMy_honour_icon = (ImageView) view.findViewById(R.id.my_honour_icon);
		mMoney = (RelativeLayout) view.findViewById(R.id.money);
		mMy_bag_icon = (ImageView) view.findViewById(R.id.my_bag_icon);
		mCollect = (RelativeLayout) view.findViewById(R.id.collect);
		mMy_collect_icon = (ImageView) view.findViewById(R.id.my_collect_icon);
		mSetting = (RelativeLayout) view.findViewById(R.id.setting);
		mMy_setting_icon = (ImageView) view.findViewById(R.id.my_setting_icon);
		eid = (TextView) view.findViewById(R.id.eid);
		group = (LinearLayout) view.findViewById(R.id.group);
		group_num = (TextView) view.findViewById(R.id.group_num);

		mMoney.setOnClickListener(this);
		mSetting.setOnClickListener(this);
		mHonour.setOnClickListener(this);
		mSex_layout.setOnClickListener(this);
		mFans.setOnClickListener(this);
		mFollow.setOnClickListener(this);
		mPost.setOnClickListener(this);
		mCollect.setOnClickListener(this);
		mAward.setOnClickListener(this);
		mGold.setOnClickListener(this);
		mQiandao.setOnClickListener(this);
		mLv.setOnClickListener(this);
		group.setOnClickListener(this);
	}

	private void initData(){
		userPrefUtils = new UserPrefUtils(getActivity());
		user=userPrefUtils.getUser();
		if(null==user)user=new User();
		imageLoaderClient = new ImageLoaderClient(getActivity());
		setData(user);
		isFirst=false;
		getHomepage();
	}

	private void setData(User onlineUser){
		if (onlineUser.getUserAuth() != null && !onlineUser.getUserAuth().getAuthentication().equals("")){
			arrow_right_layout.setVisibility(View.VISIBLE);
			auth_text.setText(onlineUser.getUserAuth().getAuthentication());
		} else {
			arrow_right_layout.setVisibility(View.GONE);
		}

		if(0==onlineUser.getSex()){
			mSex_layout.setBackgroundResource(R.drawable.girl_box);
		}else{
			mSex_layout.setBackgroundResource(R.drawable.boy_box);
		}
		glideUtils.Glidde_loadCropCircleImage(getActivity(),onlineUser.getLogo(),mIcon_user);
		if(null!=onlineUser.getUserAuth()){
			if ("-1".equals(onlineUser.getUserAuth().getType())) {
				mVip.setVisibility(View.GONE);
			} else
			if ("0".equals(onlineUser.getUserAuth().getType())) {
					mVip.setVisibility(View.VISIBLE);
					mVip.setImageResource(R.drawable.v_huan);
				} else
			if ("1".equals(onlineUser.getUserAuth().getType())) {
					mVip.setVisibility(View.VISIBLE);
					mVip.setImageResource(R.drawable.v_lan);
				}
			else
				mVip.setVisibility(View.GONE);
		}
		mLv.setText("Lv."+onlineUser.getLevel());
		mUser_name.setText(onlineUser.getNick());
		if ("".equals(onlineUser.getIntro())){
			mSign.setText("警察蜀黍，就是这个人不写签名");
		}else{
			mSign.setText(onlineUser.getIntro());
		}
		gold_num.setText(((int)onlineUser.getCoin())+"金币");
		eid.setText("Eid:"+onlineUser.getGzno());
		mNum_time.setText("被赞"+onlineUser.getLikedCount()+"次");
		mPost_num.setText(onlineUser.getPostsCount());
		mFollow_num.setText(onlineUser.getFollowsCount());
		mFans_num.setText(onlineUser.getFansCount());
		group_num.setText(onlineUser.getGroupCount());
	}
	@Override
	public void onClick(View view) {
		switch (view.getId()){
			case R.id.money:

				String gzno = userPrefUtils.getUser().getGzno();
				String phone = userPrefUtils.getUser().getPhone();
				if (!gzno.equals(phone)) {
					String pass= (String) SerializeManager.loadFile(Constant.peson_hpsw+userPrefUtils.getUser().getId());
					if(null!=pass&&!"".equals(pass)){
//						Intent intent=new Intent(getActivity(), GzRedPaperCenterActivity.class);
//						startActivity(intent);
					}else{
						getpass();
					}

				} else {
					banDingDialog();
				}

				MobclickAgent.onEvent(getActivity(),"EC_MINE_WALLET");

				break;
			case R.id.setting:
				Intent intent1 = new Intent(getActivity(), SettingActivity.class);
				startActivity(intent1);
				MobclickAgent.onEvent(getActivity(),"EC_MINE_SETTING");
				break;
			case R.id.gold:
				Intent intent=new Intent(getActivity(),GzWebViewActivityNoTitle.class);
				intent.putExtra("url", ApiConfig.USER_MY_GOLD);
				intent.putExtra("actbarTitle","我的金币");
				intent.putExtra("right_btn",true);
				startActivity(intent);
				MobclickAgent.onEvent(getActivity(),"EC_MINE_COIN");
//				Intent intent = new Intent(getActivity(), EDGVideoActivity.class);
//				startActivity(intent);
				break;
			case R.id.honour:
//				Intent intent2 = new Intent(getActivity(), UserInfoHonourActivity.class);
//				intent2.putExtra("user",user);
//				startActivity(intent2);
				break;
			case R.id.sex_layout:
				Intent intent3 = new Intent(getActivity(), MyInforMationActivity.class);
				startActivityForResult(intent3,Constant.USER_RESULT);
				MobclickAgent.onEvent(getActivity(),"EC_MINE_USER_INFO");
				break;
			case R.id.fans:
				Intent intent4 = new Intent(getActivity(), FansMembersActivity.class);
				startActivity(intent4);
				break;
			case R.id.follow:
				Intent intent5 = new Intent(getActivity(), FollowMembersActivity.class);
				startActivity(intent5);
				break;
			case R.id.post:
				Intent intent6 = new Intent(getActivity(), UserInfoActionActivity.class);
				intent6.putExtra("title","我的贴子");
				intent6.putExtra("user",user);
				startActivity(intent6);
				break;
			case R.id.collect:
				Intent intent7 = new Intent(getActivity(), UserInfoActionActivity.class);
				intent7.putExtra("user",user);
				intent7.putExtra("title","我的收藏");
				startActivity(intent7);
				MobclickAgent.onEvent(getActivity(),"EC_MINE_COLLECTION");
				break;
			case R.id.award:
				Intent intent8=new Intent(getActivity(),GzWebViewActivity.class);
				intent8.putExtra("url", ApiConfig.USER_MY_TASK);
				intent8.putExtra("actbarTitle","任务奖赏");
				intent8.putExtra("right_btn",true);
				startActivity(intent8);
				MobclickAgent.onEvent(getActivity(),"EC_MINE_MISSION");
				break;
			case R.id.qiandao:
				Intent intent9=new Intent(getActivity(),GzWebViewActivity.class);
				intent9.putExtra("url", ApiConfig.USER_SIGN_IN);
				intent9.putExtra("actbarTitle","签到");
				intent9.putExtra("right_btn",true);
				startActivity(intent9);
				MobclickAgent.onEvent(getActivity(),"EC_MINE_SIGN_BTN");
				break;
			case R.id.lv:
				Intent intent10=new Intent(getActivity(),GzWebViewActivity.class);
				intent10.putExtra("url", ApiConfig.USER_MY_EXPERIENCE);
				intent10.putExtra("actbarTitle","经验值");
				intent10.putExtra("right_btn",true);
				startActivity(intent10);
				break;
			case R.id.arrow_left_layout:
				mBg_user.setVisibility(View.VISIBLE);
				Animation animation1 = AnimationUtil.inFromLeftAnimation();
				mBg_user.setAnimation(animation1);
				animation1.startNow();
				auth_layout.setVisibility(View.GONE);
				auth_bg.setVisibility(View.GONE);
				Animation animation2 = AnimationUtil.inToRightAnimation();
				auth_layout.setAnimation(animation2);
				animation2.startNow();
				break;
			case R.id.arrow_right_layout:
				auth_layout.setVisibility(View.VISIBLE);
				auth_bg.setVisibility(View.VISIBLE);
				Animation animation3 = AnimationUtil.inFromRightAnimation();
				auth_layout.setAnimation(animation3);
				animation3.startNow();
				mBg_user.setVisibility(View.GONE);
				Animation animation4 = AnimationUtil.outToLeftAnimation();
				mBg_user.setAnimation(animation4);
				animation4.startNow();
				break;
			case R.id.group:
				Intent intent11 = new Intent(getActivity(), GzMyGroupListActivity.class);
				startActivity(intent11);
				break;
		}
	}


	@Override
	public void onHiddenChanged(boolean isVisibleToUser) {
		super.onHiddenChanged(isVisibleToUser);
		if(!isVisibleToUser){
			initData();
		}
	}
	private void getpass() {
		if (isLoading) {
			return;
		}
		RechargeApi rechargeApi=new RechargeApi(getActivity());
		RechargeParam atMeParam = new RechargeParam();
		atMeParam.setUserId(user.getId() + "");
		rechargeApi.getPass(atMeParam,this);
	}
	private void getHomepage(){
		UserParam userParam=new UserParam();
		userParam.setUserId(user.getId());
//		userParam.setToUserId(user.getId());
		new UserApi(getActivity()).gethomepage(userParam,this);
	}

	@Override
	public void onStart(String tag) {
		isLoading = true;
		if (isFirst) {
			showDialog(StringUtils.getString(R.string.getting), true);
			isFirst = false;
		}
	}

	@Override
	public void onSuccess(String response, String tag) {
		isLoading = false;
		dismissDialog();
		if (JSONHelper.isSuccess(response)) {
			if(ApiConfig.APIURL.URL_GetPAYPWD.equals(tag)){
				JSONObject jsonObject = null;
				try {
					jsonObject = new JSONObject(response);
					String psw=jsonObject.optString("data");
					if(null!=psw&&!"".equals(psw)){
//						SerializeManager.saveFile( CryptUtil.md5(psw), Constant.peson_hpsw+user.getId());
//						Intent intent5=new Intent(getActivity(), GzRedPaperCenterActivity.class);
//						startActivity(intent5);
					}else{
						setPassDialog();
					}
				} catch (JSONException e) {
					e.printStackTrace();
				}

			}else if(tag.equals(ApiConfig.APIURL.URL_HOMEPAGE)) {
				UserHomeData userData = JsonUtil.getMode(response, UserHomeData.class);
				if(null!=userData&&null!=userData.getData()&&null!=userData.getData().getUser()){
					setData(userData.getData().getUser());
				}
			}
		}else{
			try {
				Toast.makeText(getActivity(),"请求失败，请重试",Toast.LENGTH_SHORT).show();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

	@Override
	public void onFaile(VolleyError volleyError, String tag) {
		isLoading = false;
		dismissDialog();
		ResultCode.toastVolleyError(getActivity(), volleyError);
	}
	private void banDingDialog() {
		final DeleteDialog dialog = DeleteDialog.create(getActivity(), true);
		dialog.show();
		dialog.setCancelable(true);
		dialog.setTitle(StringUtils.getString(R.string.prompt));
		dialog.setContent("使用红包功能,\n需要绑定一个安全手机号");
		dialog.setSubmittext("立即绑定");
		dialog.setCancelListener(new DeleteDialog.CancelClickListener() {

			@Override
			public void cancelClick() {
				dialog.dismiss();
			}
		});
		dialog.setSubmitListener(new DeleteDialog.SubmitClickListener() {

			@Override
			public void submitClick() {
				Intent intent = new Intent(getActivity(),
						GzBindPhomeActivity.class);
				intent.putExtra("frompage", "hongbao");
				startActivity(intent);
				dialog.dismiss();

			}
		});
	}
	private void setPassDialog() {
		final DeleteDialog dialog = DeleteDialog.create(getActivity(), true);
		dialog.show();
		dialog.setCancelable(true);
		dialog.setTitle(StringUtils.getString(R.string.prompt));
		dialog.setContent("使用红包功能,\n需要设置独立的支付密码");
		dialog.setSubmittext("立即设置");
		dialog.setCancelListener(new DeleteDialog.CancelClickListener() {

			@Override
			public void cancelClick() {
				dialog.dismiss();
			}
		});
		dialog.setSubmitListener(new DeleteDialog.SubmitClickListener() {

			@Override
			public void submitClick() {
				Intent intent = new Intent(getActivity(),
						GzPayPassForgetActivity.class);
				intent.putExtra("frompage", "setpass");
				startActivity(intent);
				dialog.dismiss();

			}
		});
	}

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, data);
		if (resultCode == Activity.RESULT_OK) {
			if (requestCode == Constant.USER_RESULT) {
				User user1= (User) data.getSerializableExtra("user");
				if(null!=user1) {
					glideUtils.Glidde_loadCropCircleImage(getActivity(), user1.getLogo(), mIcon_user);
					mUser_name.setText(user1.getNick());
					if ("".equals(user1.getIntro())) {
						mSign.setText("警察蜀黍，就是这个人不写签名");
					} else {
						mSign.setText(user1.getIntro());
					}
				}
			}
		}
	}

	public static MeFragment newInstance() {
		MeFragment f = new MeFragment();
		Bundle args = new Bundle();
		f.setArguments(args);
		return f;
	}
}
